package com.tianji.promotion.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.utils.CollUtils;
import com.tianji.promotion.constants.PromotionConstants;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.domain.po.ExchangeCode;
import com.tianji.promotion.domain.vo.ExchangeCodePageVO;
import com.tianji.promotion.mapper.ExchangeCodeMapper;
import com.tianji.promotion.query.CodeQuery;
import com.tianji.promotion.service.IExchangeCodeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.tianji.promotion.utils.CodeUtil.generateCode;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-04-18
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {
    private final StringRedisTemplate redisTemplate;
    private static final String COUPON_CODE_SERIAL_KEY = "coupon:code:serial";
    private static final String COUPON_RANGE_KEY = "coupon:code:range";
    private static final String COUPON_CODE_MAP_KEY = "coupon:code:map";

    @Override
    @Async
    public void asyncGenerateCode(Coupon coupon) {
        Integer totalNum = coupon.getTotalNum();
        Long increment = redisTemplate.opsForValue().increment(PromotionConstants.COUPON_CODE_SERIAL_KEY, totalNum);
        if (increment == null){
            return;
        }
        ArrayList<ExchangeCode> list = new ArrayList<>(totalNum);
        int maxSerialNum=increment.intValue();
        for (int i =maxSerialNum-totalNum+1; i <=maxSerialNum; i++){
            String code = generateCode(i, coupon.getId());
            ExchangeCode e = new ExchangeCode();
            e.setCode(code);
            e.setId(i);
            e.setExchangeTargetId(coupon.getId());
            e.setExpiredTime(coupon.getIssueEndTime());
            list.add(e);
            /*// 3.保存到redis中
            redisTemplate.opsForValue().setBit(COUPON_CODE_MAP_KEY, Long.parseLong(code),false);*/
        }
        saveBatch(list);
        // 4.写入Redis缓存，member：couponId，score：兑换码的最大序列号
        redisTemplate.opsForZSet().add(PromotionConstants.COUPON_RANGE_KEY, coupon.getId().toString(), maxSerialNum);
    }

    @Override
    public PageDTO<ExchangeCodePageVO> queryExchangeCodePage(CodeQuery query) {
        Page<ExchangeCode> page = this.lambdaQuery()
                .eq(ExchangeCode::getExchangeTargetId, query.getCouponId())
                .eq(query.getStatus() != null,ExchangeCode::getStatus, query.getStatus())
                .page(query.toMpPageDefaultSortByCreateTimeDesc());
        List<ExchangeCode> records = page.getRecords();
        if (CollUtils.isEmpty(records)){
            return PageDTO.empty(page);
        }
        ArrayList<ExchangeCodePageVO> list = new ArrayList<>(records.size());
        for (ExchangeCode record : records) {
            ExchangeCodePageVO code = BeanUtil.copyProperties(record, ExchangeCodePageVO.class);
            list.add(code);
        }
        return PageDTO.of(page, list);
    }
}
